package com.frank.yinyuetai.Fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.frank.yinyuetai.Adapter.HomeRecycleAdapter;
import com.frank.yinyuetai.Bean.VideoBean;
import com.frank.yinyuetai.R;
import com.frank.yinyuetai.Util.URLProviderUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/8/17 0017.
 */
public class HomeFragment extends Fragment {
    @Bind(R.id.rv_home)
    RecyclerView recyclerView;
    @Bind(R.id.fa_btn_home)
    FloatingActionButton floatingActionButton;
    @Bind(R.id.srl_home)
    SwipeRefreshLayout swipeRefreshLayout;
    private List<VideoBean> mList;
    protected int mWidth;
    protected int mHeight;
    private int offset = 0;
    private int size = 20;
    private HomeRecycleAdapter homeRecycleAdapter;
    protected int lastVisibleItem;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.home_fragment_layout, null);
        ButterKnife.bind(this, view);
        mList = new ArrayList<>();
        observerView(540, 640);
        //务必在初始化宽高后面
        homeRecycleAdapter = new HomeRecycleAdapter(mList, mWidth, mHeight, getActivity());
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(homeRecycleAdapter);
        initView();
        view.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
                requestData(true);
            }
        }, 100);
        return view;
    }


    private void initView() {
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                recyclerView.smoothScrollToPosition(0);
            }
        });

        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestData(true);
            }
        });

    }

    private void requestData(boolean isFirst) {
        if (isFirst) {
            offset = 0;
        } else {
            offset = offset + 20;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils.getInstance()
                        .get(URLProviderUtil.getMainPageUrl(offset, size))
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                Gson gson = new Gson();
                                List<VideoBean> vList = gson.fromJson(s, new TypeToken<List<VideoBean>>() {
                                }.getType());
                                mList.addAll(vList);
                                Message message = new Message();
                                message.what = 1;
                                handler.sendMessage(message);
                            }

                            @Override
                            public void onAfter(@Nullable String s, @Nullable Exception e) {
                                super.onAfter(s, e);
                                swipeRefreshLayout.setRefreshing(false);
                            }

                        });
            }
        }).start();

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {

//                homeRecycleAdapter.notifyDataSetChanged();
                recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
                    @Override
                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                        super.onScrollStateChanged(recyclerView, newState);
                        if (newState == RecyclerView.SCROLL_STATE_IDLE && (lastVisibleItem + 1 == homeRecycleAdapter.getItemCount())) {
                            swipeRefreshLayout.setRefreshing(true);
                            requestData(false);
                        }
                    }

                    @Override
                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                        super.onScrolled(recyclerView, dx, dy);
                        lastVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
                    }
                });
            }
        }

    };


    protected void observerView(int imgHeight, int imgWidth) {
        DisplayMetrics metric = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
        mWidth = metric.widthPixels;
        mHeight = (mWidth * imgHeight) / imgWidth;
    }
}
